package com.am.server.common.base.advice;

import com.am.server.common.base.model.entity.BaseEntity;
import com.am.server.common.base.model.entity.EditableEntity;
import com.am.server.common.base.service.CommonService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.Collection;

@Aspect
@Component
public class RepositorySaveAdvice {
    private final CommonService commonService;

    public RepositorySaveAdvice(CommonService commonService) {
        this.commonService = commonService;
    }

    /**
     * 实体公共字段赋值
     *
     * @param pjp pjp
     * @return Object
     */
    @Around("execution(* *..*Repository.save(..))")
    public Object save(ProceedingJoinPoint pjp) throws Throwable {
        Object arg = pjp.getArgs()[0];
        if (arg instanceof BaseEntity entity) {
            beforeSave(entity);
        }
        return pjp.proceed();
    }

    /**
     * 实体公共字段赋值
     *
     * @param pjp pjp
     * @return Object
     */
    @Around("execution(* *..*Repository.saveAll(..))")
    public Object saveAll(ProceedingJoinPoint pjp) throws Throwable {
        Object arg = pjp.getArgs()[0];
        if (arg instanceof Collection<?> collection) {
            collection.stream().filter(BaseEntity.class::isInstance).map(BaseEntity.class::cast).forEach(this::beforeSave);
        }
        return pjp.proceed();
    }

    private void beforeSave(BaseEntity entity) {
        if (entity instanceof EditableEntity editableEntity) {
            commonService.beforeSave(editableEntity);
        } else {
            commonService.beforeSave(entity);
        }
    }
}
